<template>
  <!-- 导航栏 -->
  <uni-nav-bar class="nav-bar" fixed="true" statusBar="true" :border="false">
    <div class="nav-bar-center">
      <div class="title ellipsis"> {{ currentQuestionnaire?.title ?? '' }} </div>
    </div>
  </uni-nav-bar>
  <!-- 页面主体 -->
  <div class="container">
    <!-- 问卷头部 -->
    <div class="questionnaire-head">
      <!-- 问卷封面 -->
      <div class="head-cover">
        <image class="img" :src="fixQuestionnaireCover(currentQuestionnaire?.coverImg)" mode="aspectFill" />
      </div>
      <!-- 问卷标题 -->
      <div class="head-title ellipsis">{{
        currentQuestionnaire?.title ?? '' }} </div>
      <!-- 问卷描述 -->
      <div class="questionnaire-describe"> {{
        currentQuestionnaire?.desc ?? '' }} </div>
    </div>
    <!-- 问卷内容 -->
    <div class="content">
      <!-- 不同的问题类型的区块 -->
      <div :class="questionList.questionCategory === identityQuestionCategoryName ? 'identity-block' : 'normal-block'"
        v-for="  (questionList, questionListIndex)   in   currentQuestionnaire?.categoryQuestionList  "
        :key="questionList.id">

        <!-- 身份信息问题特有的结构 -->
        <div class="question" v-if="questionList.questionCategory === identityQuestionCategoryName">
          <text class="title">您的身份是？</text>
          <questionnaire-radio-group class="radio-group" v-model="questionList.questionList[0].options"
            :disable="currentQuestionnaire?.isAnswered"></questionnaire-radio-group>
        </div>

        <!-- 一般问题特有的结构 -->
        <!-- 问题类别 -->
        <div class="question-type" v-if="isShowQuestionList(questionList)">
          问题类别：{{ questionList.questionCategory }}
        </div>
        <!-- 问题列表 -->
        <div class="question-list" v-if="isShowQuestionList(questionList)">
          <div class="question" v-for="(  question, questionIndex  ) in   questionList.questionList  " :key="question.id">
            <text class="question-title">Q{{ questionIndex + 1 }}: {{ question.title }}</text>
            <!-- 数字或手机号码输入框 -->
            <input v-if="question.type === 'inputNum' || question.type === 'inputPhone'" class="question-input"
              :value="question.answer" type="number" :placeholder="question?.placeholder || '请输入内容'"
              :data-question-index="[questionListIndex, questionIndex]" @input="inputHandle" />
            <!-- 日期选择器 -->
            <picker v-else-if="question.type === 'pickDate'" class="date-picker" mode="date"
              :data-question-index="[questionListIndex, questionIndex]" @change="inputHandle">
              <div class="date" :class="question.answer ? '' : 'placeholder'">{{ question.answer || '请输入内容' }}</div>
            </picker>
            <!-- 文本输入框 -->
            <textarea v-else class="question-input" :value="question.answer" auto-height
              :placeholder="question?.placeholder || '请输入内容'" :data-question-index="[questionListIndex, questionIndex]"
              @input="inputHandle" />
          </div>
        </div>
      </div>
      <!-- 结束语 -->
      <div class="conclusion">
        {{ currentQuestionnaire?.conclusion ?? '' }}
      </div>
      <!-- 提交按钮 -->
      <button class="submit-btn" @click="submitBtnClickHandle">
        提交
      </button>
    </div>
  </div>
  <!-- 「查看问卷」悬浮按钮 -->
  <div class="float-btn" @click="floatBtnClickHandle" v-if="currentQuestionnaire?.isAnswered">
    <image class="icon" src="@/static/icons/common/eye-2.svg" mode="aspectFill" />
    <text class="text">查看问卷</text>
  </div>
  <!-- 「有未答完题目」提示弹窗 -->
  <uni-popup ref="tipPopup" type="dialog">
    <uni-popup-dialog mode="base" title=" " type="warn" content="还有未答完的题目，确定要提交吗？" cancelText="取消" confirmText="确定"
      @close="tipCancelHandle" @confirm="tipConfirmHandle"></uni-popup-dialog>
  </uni-popup>
  <!-- 对方未填写问卷提示对话框 -->
  <uni-popup ref="partnerNoSurveyPopup" type="dialog">
    <div class="no-survey-popup-dialog">
      <span class="no-survey-popup-dialog-title">提示</span>
      <span class="no-survey-popup-dialog-content">{{ targetIdentityZh }}暂未填写该问卷，您可以将问卷转发Ta，Ta填写完成后您即可查看</span>
      <div class="no-survey-popup-dialog-cancel-btn" @click="targetUnansweredTipCancel">
        <button class="button">取消</button>
      </div>
      <div class="no-survey-popup-dialog-confirm-btn" @click="targetUnansweredTipConfirm">
        <button class="button" open-type="share" :data-id="questionnaireId"
          :data-title="currentQuestionnaire?.title">转发</button>
      </div>
    </div>
  </uni-popup>
</template>

<script lang="ts" setup>
import { getCurrentInstance } from 'vue'
import { useQuestionnaire } from '@/stores/questionnaire'
import { onHide, onLoad, onShareAppMessage } from '@dcloudio/uni-app';
import QuestionnaireRadioGroup from '@/components/questionnaire-radio-group.vue'
import { storeToRefs } from 'pinia';
import { identityMap, identityQuestionCategoryName } from '@/static/constants/questionnaire-constant';
import { navigateTo } from '@/utils/navigate';
import { getLocalToken } from '@/utils/token';
import { fixQuestionnaireCover, getQuestionnaireUnselectedIdentity, getQuestionnaireUnselectedIdentityZh, shareQuestionnaire } from '@/utils/others';
import { useUser } from '@/stores/user-store';
import { ref } from 'vue';
import { computed } from '@vue/reactivity';

const questionnaire = useQuestionnaire()
const { saveCurrentQuestionnaireToLocal, updateAnswer, getAndSetCurrentQuestionnaireAnswer } = questionnaire

const { currentQuestionnaire, questionnaireAnswerStatus } = storeToRefs(questionnaire)
const { getAndSetQuestionnaireAnswerStatus } = questionnaire

const userStore = useUser()
const { userInfo } = storeToRefs(userStore)

/** 当前组件实例 */
const currentInstance = getCurrentInstance()

//#region 保存已输入的内容功能

/** 文本框输入事件 */
const inputHandle = (e: any) => {
  console.log('inputHandle', e)
  const questionIndx = e?.currentTarget?.dataset?.questionIndex || []
  const answer = e?.detail.value

  // 更新当前问题的答案
  updateAnswer(questionIndx, answer)
  // 将当前问卷保存到本地
  saveCurrentQuestionnaireToLocal('answer')
}

//#endregion

// #region 当前回答问卷和对方回答问卷情况相关

/** 当前问卷的问卷id */
let questionnaireId = ''

onLoad(async (options: any) => {
  questionnaireId = options.questionnaireId
  await getAndSetQuestionnaireAnswerStatus(questionnaireId)

  // XXX 为了防止首次通过分享进入页面时，没有token，无法正常获取问卷信息，所以暂时使用这种方法，后续需要通过改造request来解决
  const timer = setInterval(() => {
    if (getLocalToken()) {
      clearInterval(timer)
      // 获取并设置当前问卷的答案
      getAndSetCurrentQuestionnaireAnswer(options.questionnaireId)
    }
  }, 50)
})


//#endregion


/** 根据questionList判断是否显示该结构 */
const isShowQuestionList = (questionList: CategoryQuestion) => {
  return questionList.questionCategory != identityQuestionCategoryName
    && questionList.questionList.length > 0
}

/** 是否有未答的题目 */
const hasUnansweredQuestion = () => {
  let hasUnansweredQuestion = false
  currentQuestionnaire.value?.categoryQuestionList?.forEach(questionList => {
    if (questionList.questionCategory === identityQuestionCategoryName) {
      return
    }
    // 查找是不是有question.answer为空或未定义，如果有，则修改hasUnansweredQuestion
    questionList.questionList.find(question => {
      if (!question.answer) {
        hasUnansweredQuestion = true
      }
    })
  })
  return hasUnansweredQuestion
}

/** 「提交」按钮点击事件 */
const submitBtnClickHandle = async () => {
  // 如果有未答完的题目，则弹出提示弹窗
  if (hasUnansweredQuestion()) {
    toggleTipPopup(true)
    return
  }

  try {
    // 没有未答完的题目，则直接提交
    await questionnaire.submitCurrentQuestionnaire()
    // 提交成功后，跳转到「提交成功」页面

    navigateTo('questionnaire-submission-success', {
      questionnaireId: currentQuestionnaire.value?.id || '',
      targetIdentity: getQuestionnaireUnselectedIdentity(currentQuestionnaire.value) || ''
    })
  } catch (e) {
    console.error('submitCurrentQuestionnaire', e)
  }
}

//#region 「有未答完题目」提示弹窗相关

/**
 * 切换提示弹窗显示
 * @param isOpen 是否显示
 */
const toggleTipPopup = (isOpen: boolean) => {
  console.log('instance', currentInstance)
  const tipPopup: any = currentInstance!.refs.tipPopup
  if (isOpen) {
    tipPopup.open()
  } else {
    tipPopup.close()
  }
}

/** 「有未答完题目」提示弹窗-取消按钮点击事件 */
const tipCancelHandle = () => {
  toggleTipPopup(false)
}

/** 「有未答完题目」提示弹窗-确定按钮点击事件 */
const tipConfirmHandle = async () => {
  toggleTipPopup(false)
  isNavigateToOthers = true

  try {
    await questionnaire.submitCurrentQuestionnaire()
    // 提交成功后，跳转到「提交成功」页面
    navigateTo('questionnaire-submission-success', {
      questionnaireId: currentQuestionnaire.value?.id || '',
      targetIdentity: getQuestionnaireUnselectedIdentity(currentQuestionnaire.value) || ''
    })
  } catch (e) {
    console.error('submitCurrentQuestionnaire', e)
  }
}

//#endregion

//#region 监听页面消失

/** 是否是要跳转到其他页面 */
let isNavigateToOthers = false
// 监听页面消失
onHide(() => {
  // 如果是要跳转到「查看已回答问卷」页面，则不需要跳转到「聊天」页面
  if (isNavigateToOthers) {
    isNavigateToOthers = false
    return
  }
   navigateTo('survey')
})

//#endregion

//#region 「查看问卷」悬浮按钮相关
/** 对方身份名称（中文） */
const targetIdentityZh = computed(() => {
  // 如果还没提交过问卷，则默认为「新娘」
  if (!currentQuestionnaire.value?.isAnswered) {
    return '新娘'
  }

  return getQuestionnaireUnselectedIdentityZh(currentQuestionnaire.value)
})


/** 「对方未填写问卷」提示对话框切换显示 */
const toggleNoSurvey = (isOpen: boolean) => {
  const targetUnansweredTip: any = currentInstance!.refs.partnerNoSurveyPopup
  if (isOpen) {
    targetUnansweredTip.open()
  } else {
    targetUnansweredTip.close()
  }
}

/** 「对方未填写问卷」提示对话框-取消按钮点击事件 */
const targetUnansweredTipCancel = () => {
  toggleNoSurvey(false)
}

/** 「对方未填写问卷」提示对话框-确定按钮点击事件 */
const targetUnansweredTipConfirm = () => {
  toggleNoSurvey(false)
}

/** 「对方未填写问卷」提示对话框-「分享」回调 */
onShareAppMessage((res) => {
  return shareQuestionnaire(res, userInfo.value.name, userInfo.value.id)
})

/** 「查看问卷」悬浮按钮点击事件 */
const floatBtnClickHandle = () => {
  isNavigateToOthers = true
  /** 身份选择问题 */
  const identityQuestion = currentQuestionnaire?.value?.categoryQuestionList?.find(
    questionList => {
      return questionList.questionCategory === identityQuestionCategoryName
    })?.questionList?.[0]
  /** 未选择的身份（中文） */
  const unselectedIdentityZh = identityQuestion?.options?.find(option => {
    return !option.checked
  })?.option
  /** 未选择的身份（英文） */
  const unselectedIdentity = identityMap.find(identity => {
    return identity.zh === unselectedIdentityZh
  })?.en

  /** 对方身份回答情况 */
  const targetIdentityAnswer = questionnaireAnswerStatus.value?.find(answerStatus => {
    return answerStatus.identity === unselectedIdentity
  })?.isAnswered

  // 如果对方未回答，则弹出提示弹窗
  if (!targetIdentityAnswer) {
    toggleNoSurvey(true)
    return
  }

  navigateTo('questionnaire-view-answer', {
    questionnaireId: currentQuestionnaire.value?.id || '',
    targetIdentity: unselectedIdentity || '',
  })
}

//#endregion
</script>

<style lang="scss" scoped>
@import '@/static/styles/questionnaire.scss';

.container {
  display: grid;
  grid-template:
    'head' 78.2051vw
    'content' auto;

  position: relative;

  // 问卷头部
  .questionnaire-head {
    width: 100vw;
    background-color: #ffffff;

    padding: 16px;
    box-sizing: border-box;
    display: grid;
    grid-template:
      'cover' 37.9487vw
      '.' 16px
      'title' 8.7179vw
      '.' 8px
      'desc' 1fr;
    justify-items: center;

    // 头图
    .head-cover {
      grid-area: cover;
    }

    // 问卷标题
    .head-title {
      grid-area: title;
    }

    // 问卷描述
    .questionnaire-describe {
      grid-area: desc;
    }
  }

  // 问卷内容
  .content {
    grid-area: content;

    display: flex;
    flex-direction: column;
    align-items: center;

    // 身份问题区块
    .identity-block {
      margin-top: 8px;
      width: 100%;
      background-color: #fff;

      .question {
        width: 100%;
        height: 22.8205vw;

        box-sizing: border-box;
        padding: 16px;
        display: grid;
        grid-template:
          'title more' 5.3846vw
          'radio-group radio-group' 1fr
          / 1fr 4.6154vw;
        grid-row-gap: 12px;

        // 身份问题标题
        .title {
          grid-area: title;
          font-size: 3.8462vw;
        }

        .more-icon {
          grid-area: more;
          justify-self: end;
        }

        .radio-group {
          grid-area: radio-group;
        }
      }
    }
  }

  // 一般问题区块
  .normal-block {
    margin-top: 8px;
    width: 100%;

    // 问题类别
    .question-type {
      padding: 16px 0 8px 16px;
      font-size: 4.6154vw;
      color: #17ce92;
      background-color: #fff;
    }

    // 问题列表
    .question-list {
      width: 100%;
      display: grid;
      grid-auto-rows: minmax(20.2564vw auto);

      // 问题
      .question {
        box-sizing: border-box;
        background-color: #fff;


        padding: 8px 16px;
        display: grid;
        grid-template:
          'title more' auto
          'input input' minmax(8.7179vw, auto) / 1fr 46.15rpx;
        grid-row-gap: 8px;
        align-items: center;

        .question-title {
          grid-area: title;
          font-size: 28.85rpx;
          color: #ff5875;
        }

        .more-icon {
          align-self: self-start;
          grid-area: more;
          justify-self: end;
        }

        .question-input {
          grid-area: input;

          width: calc(100% - 24px);
          background-color: #f4ebf1;
          border-radius: 2px;

          padding: 8px 12px;
          font-size: 25rpx;
        }

        // 日期选择器
        .date-picker {
          grid-area: input;
          width: calc(100% - 24px);
          background-color: #f4ebf1;
          border-radius: 2px;

          padding: 8px 12px;
          font-size: 25rpx;

          .date {

            &.placeholder {
              color: #808080;
            }
          }

        }
      }
    }
  }
}

// 结束语
.conclusion {
  margin-top: 24px;
}

// 「提交」按钮
.submit-btn {
  width: 358px;
  height: 42px;
  border-radius: 4px;

  display: flex;
  justify-content: center;
  align-items: center;

  font-size: 16px;

  background: #17ce92;
  color: #ffffff;
}

// 「查看问卷」悬浮按钮
.float-btn {
  position: fixed;
  bottom: 75.3846vw;
  right: 0;

  width: 106px;
  height: 32px;
  opacity: 0.6;
  background: #000000;
  border-radius: 16px 0 0 16px;

  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;

  .icon {
    width: 18px;
    height: 18px;
    color: #ffffff;
  }

  .text {
    margin-left: 4px;
    font-size: 15px;
    color: #ffffff;
  }
}

// 对方未回答提示弹窗
.no-survey-popup-dialog {
  width: 300px;
  background-color: #fff;

  border-radius: 11px;
  overflow: hidden;

  display: grid;
  grid-template:
    'title title' 50px
    'content content' 1fr
    'cancel-btn confirm-btn' 45px;

  .no-survey-popup-dialog-title {
    grid-area: title;
    align-self: end;
    justify-self: center;

    color: #909399;
    font-size: 16px;
    font-weight: 500;
  }

  .no-survey-popup-dialog-content {
    grid-area: content;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    padding: 20px;

    font-size: 14px;
    color: #6C6C6C;
  }

  .no-survey-popup-dialog-cancel-btn {
    grid-area: cancel-btn;
    overflow: hidden;

    .button {
      background-color: #fff;
      border-radius: 0;
      scale: 1.15;
      translate: 0 3px;

      font-size: 15px;
      color: #333;
    }
  }

  .no-survey-popup-dialog-confirm-btn {
    grid-area: confirm-btn;
    overflow: hidden;

    border-left-color: #f0f0f0;
    border-left-style: solid;
    border-left-width: 1px;

    .button {
      background-color: #fff;
      border-radius: 0;
      scale: 1.15;
      translate: 0 3px;

      font-size: 15px;
      color: #007aff;
    }
  }
}
</style>
